package com.etoak.common.jwt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.management.ObjectName;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    /**
     * 256bit = 32byte * 8
     */
    public static final String SECRET = "11111111111111111111111111111111";

    /**
     * 用于签名
     */
    public static final Key KEY = Keys.hmacShaKeyFor(SECRET.getBytes());

    /**
     * 12小时过期
     */
    public static final long EXPIRE = 1000 * 60 * 60 * 12;

    /**
     * 生成JWT
     *
     * @param claimsMap 自定义内容
     */
    public static String create(Map<String, Object> claimsMap) {
        Date issueDate = new Date();
        return Jwts.builder().signWith(KEY, SignatureAlgorithm.HS256)
                .setClaims(claimsMap)
                .setIssuedAt(issueDate)
                .setExpiration(new Date(issueDate.getTime() + EXPIRE))
                .compact();
    }

    public static Map<String, Object> parse(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public static void main(String[] args) {

        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put("id", 1);
        claimsMap.put("username", "123");
        String s = create(claimsMap);
        System.out.println(s);
//        System.out.println(parse("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiIxMjMiLCJpYXQiOjE3MjM2ODgxNTQsImV4cCI6MTcyMzczMTM1NH0.AaIZH1pzPxogDWZM6mFzONBWPyBGRZqzSMRq6CN31-c"));

    }
}
